#pragma once
#include <iostream>
#include <functional>
#include "InetAddr.hpp"
#include "Socket.hpp"
#include "log.hpp"
#include "Protocol.hpp"


using process_t  = function<shared_ptr<Response>(shared_ptr<Request>)>;


class IoService
{
public:
	IoService(process_t process):_process(process)
	{};
	void Execute(SockSPtr sock,InetAddr &addr)
	{
		std::string packagestream;
		while(true)
		{
			//1.读取
			ssize_t  n =sock->Recv(&packagestream);
			if(n<=0)
			{
				LOG(INFO,"n:%d\n",n);
				LOG(INFO,"client quit or recv err\n");
				break;
			};
			std::cout << "--------------------------------------------" << std::endl;
        	  	std::cout << "packagestream: \n" << packagestream << std::endl;
			//2.提取有效载荷
			std::string package = Decode(packagestream);
			if(package.size()==0)
				continue;//没有完整的有效载荷
			std::cout << "package: \n" << package << std::endl;
			//3.反序列化
			shared_ptr<Request> req = make_shared<Request>();
			req->Deserialize(package);
			//4.业务处理
			shared_ptr<Response> res=_process(req);
			//5.序列化
			std::string jsonres;
			res->Serialize(&jsonres);
			std::cout << "jsonres: \n" << jsonres << std::endl;
			//6.添加报头
			jsonres=Encode(jsonres);
			std::cout << "jsonres add header done: \n" << jsonres << std::endl;
			//7.发送出去
			sock->Send(jsonres);

		};
	};
	


process_t _process;
};
